﻿using System;
using System.Linq;
using System.Web.Mvc;
using Enyim.Caching;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SilenthinkCommon.Extension;
using SilenthinkContract;
using SilenthinkContract.Component;
using Web.Areas.Auction.Models;
using Web.Controllers;

namespace Web.Areas.Auction.Controllers
{
    public class HomeController : BaseController
    {
        private readonly int dueDay = 7;


        public HomeController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient) : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        public ActionResult Index(int page = 1, int size = 20)
        {
            var model = new HomeControllerModel.Index();
            model.Auctions = AuctionService.GetPagedAuction(page, size).ToPagedList(page, size);
            return View(model);
        }

        public ActionResult Auctions()
        {
            var auctions =
                AuctionService.GetAllAuction().Select(o => new { BeginTime = o.StartDateTime, o.ExpectedTime, UserId = o.UserId, NickName = o.NickName, o.Id, o.Interval, o.BidPrice, o.Status, Remain = o.ExpectedTime.HasValue ? DateDiff(o.ExpectedTime.Value) : o.Interval });

            var data = JsonConvert.SerializeObject(auctions, new JavaScriptDateTimeConverter());
            return Content(data);

        }

        private static int DateDiff(DateTime dateTime)
        {
            return (int)dateTime.Subtract(DateTime.Now).TotalSeconds;
        }

        public ActionResult List()
        {
            var model = new HomeControllerModel.List();
            model.Auctions = AuctionService.GetAllAuction();
            return View(model);
        }

        /// <summary>
        /// 购买
        /// </summary>
        /// <param name="param">拍品Id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Buy(long? param)
        {
            var identity = User.Identity.SkIdentity();
            var model = new HomeControllerModel.Buy();
            if (param.HasValue && param.Value > 0)
            {
                model.Auction = AuctionService.GetAuction(param.Value);
                model.AuctionOrderId = OrderService.GetAuctionOrderId(identity.Id, param.Value);
                if (string.IsNullOrEmpty(model.AuctionOrderId))
                {
                    model.SumBid = AuctionService.SumBid(identity.Id, param.Value);
                }
            }
            return PartialView(model);
        }

        /// <summary>
        /// 确认购买
        /// </summary>
        /// <param name="param">拍品Id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmBuy(long param)
        {
            var result = new SkResult<string>();
            var identity = User.Identity.SkIdentity();

            var auction = AuctionService.GetAuction(param);
            if (!auction.DiffBuySupported)
            {
                result.Message = "该拍品不支持补差购买！";
            }
            else
            {
                if (auction.TransactionTime.HasValue && (DateTime.Now < auction.TransactionTime.Value.AddDays(dueDay)))
                {
                    if (auction.DiffBuyLimitationValue > 0)
                    {
                        var auctionOrderId = OrderService.GetAuctionOrderId(identity.Id, param);
                        if (string.IsNullOrEmpty(auctionOrderId))
                        {
                            var bidPrice = AuctionService.SumBid(identity.Id, param) / 2;
                            var price = auction.BuyPrice - bidPrice;
                            auction.BuyPrice = price;
                        }
                        var order = auction.GenerateOrder(identity.Id, User.Identity.Name, identity.NickName, GetIpAddress());
                        var status = OrderService.CreateOrder(order);
                        if (status)
                        {
                            result.Status = true;
                            result.Data = order.Id;
                        }
                        else
                        {
                            result.Message = "生成订单失败！请重试。";
                        }
                    }
                    else
                    {
                        result.Message = "超出购买限制。";
                    }
                }
                else
                {
                    result.Message = "超出购买时限。";
                }
            }

            return Json(result);
        }
    }
}
